package com.fc.test.util;

import java.sql.Timestamp;
import java.text.*;
import java.util.*;

public class DateUtil
{

    public static final String C_DATE_DIVISION = "-";
    public static final String C_TIME_PATTON_DEFAULT = "yyyy-MM-dd HH:mm:ss";
    public static final String C_DATE_PATTON_DEFAULT = "yyyy-MM-dd";
    public static final String C_DATA_PATTON_YYYYMMDD = "yyyyMMdd";
    public static final String C_TIME_PATTON_HHMMSS = "HH:mm:ss";
    public static final int C_ONE_SECOND = 1000;
    public static final int C_ONE_MINUTE = 60000;
    public static final int C_ONE_HOUR = 0x36ee80;
    public static final long C_ONE_DAY = 0x5265c00L;

    public DateUtil(){ }


    public static double dateDiff(String startTime, String endTime,
                                String format, String str) {
        // 按照传入的格式生成一个simpledateformate对象
        SimpleDateFormat sd = new SimpleDateFormat(format);
        long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
        long nh = 1000 * 60 * 60;// 一小时的毫秒数
        long nm = 1000 * 60;// 一分钟的毫秒数
        long ns = 1000;// 一秒钟的毫秒数
        long diff;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        // 获得两个时间的毫秒时间差异
        try {
            diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
            day = diff / nd;// 计算差多少天
            hour = diff % nd / nh + day * 24;// 计算差多少小时
            min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟
            sec = diff % nd % nh % nm / ns;// 计算差多少秒
            // 输出结果
            System.out.println("时间相差：" + day + "天" + (hour - day * 24) + "小时"
                    + (min - day * 24 * 60) + "分钟" + sec + "秒。");
            System.out.println("hour=" + hour + ",min=" + min);
            if (str.equalsIgnoreCase("h")) {
                DecimalFormat df = new DecimalFormat("#.00");
                System.out.println();
                return hour+Double.parseDouble(df.format(min/60.00));
            } else {
                return min;
            }

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (str.equalsIgnoreCase("h")) {
            return hour+min/60;
        } else {
            return min;
        }
    }

        //返回当前年格式:yyyy
    public static String getCurrentYear(){
    	Calendar c;
		String year;
		c = new GregorianCalendar();
	    year = Integer.toString(c.get(1));
    	return year;
    }
  //返回当前月。格式:MM
    public static String getCurrentMonth(){
     	 Calendar c;
		 String year;
		 String month;
		 c = new GregorianCalendar();
	     year = Integer.toString(c.get(1));
	     int k_c = c.get(2);
	     k_c++;
	     month = Integer.toString(k_c);
	     if(month.length()==1) month="0"+month;
    	return month;
    }
  //返回当前天。格式:dd
    public static String getCurrentDay(){
    	 Calendar c;
		 String year;
		 String month;
	     String day;
	     c = new GregorianCalendar();
	     year = Integer.toString(c.get(1));
	     int k_c = c.get(2);
	     k_c++;
	     month = Integer.toString(k_c);
	     day = Integer.toString(c.get(5));
	     if(day.length()==1) day="0"+day;
    	return day;
    }
    //返回日期字符串中的年。格式:yyyy
    public static String getYear(String DateTime){
    	Date date = parseDate("yyyy-MM-dd", DateTime);
    	return format(date, "yyyy");
    }
    //返回日期字符串中的月。格式:MM
    public static String getMonth(String DateTime){
    	Date date = parseDate("yyyy-MM-dd", DateTime);
    	return format(date, "MM");
    }
    //返回日期字符串中的月。格式:IsIncluede0为1位时前面是否包含0
    public static String getMonth(String DateTime,boolean IsIncluede0 ){
    	Date date = parseDate("yyyy-MM-dd", DateTime);
    	String MonStr=format(date, "MM");
    	if(MonStr.length()==2&&MonStr.substring(0, 1).equals("0")&&IsIncluede0==false) MonStr=MonStr.substring(1, 2);
    		
    	return MonStr;
    }
  //返回日期字符串中的天。
    public static String getDay(String DateTime){
    	Date date = parseDate("yyyy-MM-dd", DateTime);
    	return format(date, "dd");
    }
  //返回日期字符串。格式:yyyy-MM-dd
    public static String  DateStr(String DateTime){
    	Date date = parseDate("yyyy-MM-dd", DateTime);
	    String dateStr=format(date, "yyyy")+"-"+format(date, "MM")+"-"+format(date, "dd");	
	    if(date==null)dateStr="";
	    return dateStr;
    }
    //返回当前时间。格式:hh:mm:ss
    public static String  getCurrentTimeStr(){
	     Calendar c;
		 String year;
		 String month;
	     String day;
	     String hour;
		 int hour_middle;
	     String minute;
	     String second;
		 String nanos;
		 String date;
	       c = new GregorianCalendar();
	       year = Integer.toString(c.get(1));
	       int k_c = c.get(2);
	       k_c++;
	       month = Integer.toString(k_c);
	       day = Integer.toString(c.get(5));
	       int j_c = c.get(10);
			hour = Integer.toString(j_c);
	       minute = Integer.toString(c.get(12));
	       second = Integer.toString(c.get(13));
	       nanos = Integer.toString(c.get(14));
		    k_c = c.get(9);
			if(k_c == 1)
	       {
			hour_middle = Integer.parseInt(hour)+12;
			hour=Integer.toString(hour_middle);
	       }
			if(month.length()==1) month="0"+month;
			if(day.length()==1) day="0"+day;
			if(hour.length()==1) hour="0"+hour;
			if(minute.length()==1) minute="0"+minute;
			if(second.length()==1) second="0"+second;
			if(nanos.length()==0) nanos="000";
			if(nanos.length()==1) nanos="00"+nanos;
			if(nanos.length()==2) nanos="0"+nanos;
			String currentTime = hour + ":" + minute + ":" +second;	
			return currentTime;
	}	 
    //返回当前时间。格式:yyyy-MM-dd hh:mm:ss
    public static String  getCurrentDateTimeStr(){
	     Calendar c;
		 String year;
		 String month;
	     String day;
	     String hour;
		 int hour_middle;
	     String minute;
	     String second;
		 String nanos;
		 String date;
	       c = new GregorianCalendar();
	       year = Integer.toString(c.get(1));
	       int k_c = c.get(2);
	       k_c++;
	       month = Integer.toString(k_c);
	       day = Integer.toString(c.get(5));
	       int j_c = c.get(10);
			hour = Integer.toString(j_c);
	       minute = Integer.toString(c.get(12));
	       second = Integer.toString(c.get(13));
	       nanos = Integer.toString(c.get(14));
		    k_c = c.get(9);
			if(k_c == 1)
	       {
			hour_middle = Integer.parseInt(hour)+12;
			hour=Integer.toString(hour_middle);
	       }
			if(month.length()==1) month="0"+month;
			if(day.length()==1) day="0"+day;
			if(hour.length()==1) hour="0"+hour;
			if(minute.length()==1) minute="0"+minute;
			if(second.length()==1) second="0"+second;
			if(nanos.length()==0) nanos="000";
			if(nanos.length()==1) nanos="00"+nanos;
			if(nanos.length()==2) nanos="0"+nanos;
			String currentDateTime = year + "-" +month + "-" + day + " " + hour + ":" + minute + ":" +second;	
			return currentDateTime;
	}	
    //返回当前时间字符串。格式:yyyyMMddhhmmss+4为随机数
    public static String  getCurrentDateTimeKeyStr(){
	     Calendar c;
		 String year;
		 String month;
	     String day;
	     String hour;
		 int hour_middle;
	     String minute;
	     String second;
		 String nanos;
		 String date;
	       c = new GregorianCalendar();
	       year = Integer.toString(c.get(1));
	       int k_c = c.get(2);
	       k_c++;
	       month = Integer.toString(k_c);
	       day = Integer.toString(c.get(5));
	       int j_c = c.get(10);
			hour = Integer.toString(j_c);
	       minute = Integer.toString(c.get(12));
	       second = Integer.toString(c.get(13));
	       nanos = Integer.toString(c.get(14));
		    k_c = c.get(9);
			if(k_c == 1)
	       {
			hour_middle = Integer.parseInt(hour)+12;
			hour=Integer.toString(hour_middle);
	       }
			if(month.length()==1) month="0"+month;
			if(day.length()==1) day="0"+day;
			if(hour.length()==1) hour="0"+hour;
			if(minute.length()==1) minute="0"+minute;
			if(second.length()==1) second="0"+second;
			if(nanos.length()==0) nanos="000";
			if(nanos.length()==1) nanos="00"+nanos;
			if(nanos.length()==2) nanos="0"+nanos;
			String currentDateTime = year + month + day + hour + minute + second;	
			int first1;
			int first2;
			int first3;
			int first4;
			String first;
			Random random = new Random();
			first1=random.nextInt(10);
			first2=random.nextInt(10);
			first3=random.nextInt(10);
			first4=random.nextInt(10);	
			first=String.valueOf(first1)+String.valueOf(first2)+String.valueOf(first3)+String.valueOf(first4);
			String keyStr=currentDateTime+first;
			
			return keyStr;
	}	
    //返回日期类型的当前日期
    public static Date getCurrentDate()
    {
        Calendar cal = Calendar.getInstance();
        Date currDate = cal.getTime();
        return currDate;
    }
    //返回日期类型的当前日期。格式:yyyy-MM-dd
    public static String getCurrentDateStr()
    {
        Calendar cal = Calendar.getInstance();
        Date currDate = cal.getTime();
        return format(currDate);
    }
    //返回当前日期。strFormat为自定义格式。
    public static String getCurrentDateStr(String strFormat)
    {
        Calendar cal = Calendar.getInstance();
        Date currDate = cal.getTime();
        return format(currDate, strFormat);
    }
    //把字符串日期格式转化为日期类型。
    public static Date parseDate(String dateValue)
    {
        return parseDate("yyyy-MM-dd", dateValue);
    }
  //把字符串日期格式转化为日期类型。
    public static Date parseDate2(String dateValue)
    {
        return parseDate("yyyy-MM-dd HH:mm:ss", dateValue);
    }
  //把字符串日期格式转化为日期类型。
    public static Date parseDateTime(String dateValue)
    {
        return parseDate("yyyy-MM-dd HH:mm:ss", dateValue);
    }
  //格式化时间
    public static Date parseDate(String strFormat, String dateValue)
    {
        if(dateValue == null)
        {
            return null;
        }
        if(strFormat == null)
        {
            strFormat = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat(strFormat);
        Date newDate = null;
        try
        {
            newDate = dateFormat.parse(dateValue);
        }
        catch(ParseException pe)
        {
            newDate = null;
        }
        return newDate;
    }
  //格式化时间
    public static String format(Date aTs_Datetime)
    {
        return format(aTs_Datetime, "yyyy-MM-dd");
    }
  //格式化时间
    public static String formatTime(Date aTs_Datetime)
    {
        return format(aTs_Datetime, "yyyy-MM-dd HH:mm:ss");
    }
  //格式化时间
    public static String format(Date aTs_Datetime, String as_Pattern)
    {
        if(aTs_Datetime == null || as_Pattern == null)
        {
            return null;
        } else
        {
            SimpleDateFormat dateFromat = new SimpleDateFormat();
            dateFromat.applyPattern(as_Pattern);
            return dateFromat.format(aTs_Datetime);
        }
    }
//格式化时间
    public static String formatTime(Date aTs_Datetime, String as_Format)
    {
        if(aTs_Datetime == null || as_Format == null)
        {
            return null;
        } else
        {
            SimpleDateFormat dateFromat = new SimpleDateFormat();
            dateFromat.applyPattern(as_Format);
            return dateFromat.format(aTs_Datetime);
        }
    }
   //得到时间
    public static String getFormatTime(Date dateTime)
    {
        return formatTime(dateTime, "HH:mm:ss");
    }

   
//格式化日期字符串
    public static String format(Timestamp aTs_Datetime, String as_Pattern)
    {
        if(aTs_Datetime == null || as_Pattern == null)
        {
            return null;
        } else
        {
            SimpleDateFormat dateFromat = new SimpleDateFormat();
            dateFromat.applyPattern(as_Pattern);
            return dateFromat.format(aTs_Datetime);
        }
    }
   //多少天之后的日期(传负值的话就是多少天之前的日期)
    public static Date addDays(Date date, int days)
    {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(5, days);
        return cal.getTime();
    }
//返回两个日期之间的天数
    public static int daysBetween(Date date1, Date date2)
    {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date1);
        long time1 = cal.getTimeInMillis();
        cal.setTime(date2);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / 0x5265c00L;
        return Integer.parseInt(String.valueOf(between_days));
    }
    //返回两个日期时间段
    public static String timeBetween(Date date1, Date date2)
    {
    	if(date1==null||date2==null) return "";
       String resultStr="";
       long miaocount=0;
       long mincount=0;
       long hourCount=0;
       long dayCount=0;
       long DAY = 24L * 60L * 60L * 1000L;
       long HOUR=60L * 60L * 1000L;
       long MIN=60L * 1000L;
       long MIAO=1000L;
       long haomiao = 0L;
       long miaolen=date2.getTime()-date1.getTime();
       if(miaolen<1000){haomiao = miaolen;}
       if(miaolen>60)miaocount=(miaolen / MIAO)%60;
           mincount=(miaolen / MIN)%60;
           hourCount=(miaolen / HOUR)%24;
           dayCount=miaolen / DAY;
       resultStr=dayCount+"天"+hourCount+"小时"+mincount+"分"+miaocount+"秒";
       if(dayCount==0)
    	   resultStr=hourCount+"小时"+mincount+"分"+miaocount+"秒";
       if(dayCount==0&&hourCount==0)
    	   resultStr=mincount+"分"+miaocount+"秒";
       if(dayCount==0&&hourCount==0&&mincount==0)
    	   resultStr=miaocount+"秒";
       if(dayCount==0&&hourCount==0&&mincount==0&&miaocount==0){
    	   resultStr=haomiao+"毫秒";
       }
        return resultStr;
    }
  //返回两个日期时间段
    public static String timeBetweenS(Date date1, Date date2){
    	long miaolen=date2.getTime()-date1.getTime();
    	 String resultStr=miaolen+"毫秒";
    	 return resultStr;
    }
    public static long getRelativeDays(Date date)
    {
        Date relativeDate = parseDate("yyyy-MM-dd", "1977-12-01");
        return (long)daysBetween(relativeDate, date);
    }

    public static Date getDateBeforTwelveMonth()
    {
        String date = "";
        Calendar cla = Calendar.getInstance();
        cla.setTime(getCurrentDate());
        int year = cla.get(1) - 1;
        int month = cla.get(2) + 1;
        if(month > 9)
        {
            date = (new StringBuilder(String.valueOf(String.valueOf(year)))).append("-").append(String.valueOf(month)).append("-").append("01").toString();
        } else
        {
            date = (new StringBuilder(String.valueOf(String.valueOf(year)))).append("-").append("0").append(String.valueOf(month)).append("-").append("01").toString();
        }
        Date dateBefore = parseDate(date);
        return dateBefore;
    }

    public static Date addDate(String date)
    {
        if(date == null)
        {
            return null;
        } else
        {
            Date tempDate = parseDate("yyyy-MM-dd", date);
            String year = format(tempDate, "yyyy");
            String month = format(tempDate, "MM");
            String day = format(tempDate, "dd");
            GregorianCalendar calendar = new GregorianCalendar(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day));
            calendar.add(5, 1);
            return calendar.getTime();
        }
    }

    /**
	 * 得到当前日期的yyyyMMdd形式字符串
	 * @return
	 */
	public static String getCurDateYYYYMMDD(){
		return format(new Date(),"yyyyMMdd");
	}
	
	/**
	 * 得到当前日期的HHmmss形式字符串
	 * @return
	 */
	public static String getCurDateHHMMSS(){
		return format(new Date(),"HHmmss");
	}
	
	/**
	 * 增减月份
	 * @param date   要处理的时间
	 * @param number 家或者减的月数 + -
	 * @return
	 */
	public static Date getLastMonth(Date date,int number){
		Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, number);
        Date theDate = calendar.getTime();
        return theDate;
	}
	
	/**
     * 某一个月第一天和最后一天
     * @param date
     * @return
     */
    public static Map<String, String> getFirstday_Lastday_Month(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, -1);
        Date theDate = calendar.getTime();
        
        //上个月第一天
        GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance();
        gcLast.setTime(theDate);
        gcLast.set(Calendar.DAY_OF_MONTH, 1);
        String day_first = df.format(gcLast.getTime());
        StringBuffer str = new StringBuffer().append(day_first).append(" 00:00:00");
        day_first = str.toString();

        //上个月最后一天
        calendar.add(Calendar.MONTH, 1);    //加一个月
        calendar.set(Calendar.DATE, 1);        //设置为该月第一天
        calendar.add(Calendar.DATE, -1);    //再减一天即为上个月最后一天
        String day_last = df.format(calendar.getTime());
        StringBuffer endStr = new StringBuffer().append(day_last).append(" 23:59:59");
        day_last = endStr.toString();

        Map<String, String> map = new HashMap<String, String>();
        map.put("first", day_first);
        map.put("last", day_last);
        return map;
    }

    /**
     * 当月第一天
     * @return
     */
    public static String getFirstDay() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        Date theDate = calendar.getTime();
        
        GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance();
        gcLast.setTime(theDate);
        gcLast.set(Calendar.DAY_OF_MONTH, 1);
        String day_first = df.format(gcLast.getTime());
        StringBuffer str = new StringBuffer().append(day_first).append(" 00:00:00");
        return str.toString();

    }
    
    /**
     * 当月最后一天
     * @return
     */
    public static String getLastDay() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        Date theDate = calendar.getTime();
        String s = df.format(theDate);
        StringBuffer str = new StringBuffer().append(s).append(" 23:59:59");
        return str.toString();

    }
    public static void main(String args[])
    {
       // String date = "2006-07-31";
      //  System.out.println(date);
      //  Date date2 = addDate(date);
        //System.out.println(date2);
      //  System.out.println(addDays(new Date(),-3));
       System.out.println(dateDiff("2019-07-01 11:30:00","2019-07-02 10:20:00","yyyy-MM-dd HH:mm:ss","h"));
    }
}

